package com.glg.springmvc;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.bind.annotation.*;

import java.security.SecureRandom;
import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {

    //Cookie 获取
    @RequestMapping("/getcookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        //String name = request.getParameter("name");
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            //将 Cookie 转成了数据流，然后进行循环
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取Cookie成功";
    }

    @RequestMapping("/getcookie2")
    public String getCookie2(@CookieValue("bite") String bite) {
        return "从Cookie中获取值, bite:"+bite;
    }


    @RequestMapping("/setsession")
    public String setSession(HttpServletRequest request){
        //从 Cookie 中获取到了SessionId，根据 SessionId 获取Session对象，如果没有获取到，就会创建一个Session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置session成功";
    }


    @RequestMapping("/getsession")
    public String getsession(HttpServletRequest request) {
        //从 Cookie 中获取到了 SessionId，根据 Session 获取 Session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取name:"+name;
    }


    @RequestMapping("/getsession2")
    public String getsession2(HttpSession session){
        String name = (String) session.getAttribute("name");
        return "从session中获取name:"+name;
    }


    @RequestMapping("/getsession3")
    public String getsession3(@SessionAttribute("name") String name){
        //String name = (String) session.getAttribute("name");
        return "从session中获取name:"+name;
    }


    @RequestMapping("/getheader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent: "+userAgent;
    }


    @RequestMapping("/getheader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent ) {
        //String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent: "+userAgent;
    }
}
